package estadao;

import com.sun.rave.web.ui.appbase.AbstractPageBean;
import encontrar.Encontrar;
import entidades.Post;
import hibernate.HibernateUtil;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version Atualizar.java
 * @version Created on 11/12/2012, 10:51:42
 * @author glaucio
 */
public class GetCSV extends AbstractPageBean {
  // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

  /**
   * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
   * This method is automatically generated, so any user-specified code inserted
   * here is subject to being replaced.</p>
   */
  private void _init() throws Exception {
  }

  // </editor-fold>
  /**
   * <p>Construct a new Page bean instance.</p>
   */
  public GetCSV() {
  }

  /**
   * <p>Callback method that is called whenever a page is navigated to,
   * either directly via a URL, or indirectly via page navigation.
   * Customize this method to acquire resources that will be needed
   * for event handlers and lifecycle methods, whether or not this
   * page is performing post back processing.</p>
   *
   * <p>Note that, if the current request is a postback, the property
   * values of the components do <strong>not</strong> represent any
   * values submitted with this request.  Instead, they represent the
   * property values that were saved for this view when it was rendered.</p>
   */
  @Override
  public void init() {
    // Perform initializations inherited from our superclass
    super.init();
    // Perform application initialization that must complete
    // *before* managed components are initialized

    // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
    // Initialize automatically managed components
    // *Note* - this logic should NOT be modified
    try {
      _init();
    } catch (Exception e) {
      log("Atualizar Initialization Failure", e);
      throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
    }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    getPost();
  }

  /**
   * <p>Callback method that is called after the component tree has been
   * restored, but before any event processing takes place.  This method
   * will <strong>only</strong> be called on a postback request that
   * is processing a form submit.  Customize this method to allocate
   * resources that will be required in your event handlers.</p>
   */
  @Override
  public void preprocess() {
  }

  /**
   * <p>Callback method that is called just before rendering takes place.
   * This method will <strong>only</strong> be called for the page that
   * will actually be rendered (and not, for example, on a page that
   * handled a postback and then navigated to a different page).  Customize
   * this method to allocate resources that will be required for rendering
   * this page.</p>
   */
  @Override
  public void prerender() {
  }

  /**
   * <p>Callback method that is called after rendering is completed for
   * this request, if <code>init()</code> was called (regardless of whether
   * or not this was the page that was actually rendered).  Customize this
   * method to release resources acquired in the <code>init()</code>,
   * <code>preprocess()</code>, or <code>prerender()</code> methods (or
   * acquired during execution of an event handler).</p>
   */
  @Override
  public void destroy() {
  }

  /**
   * <p>Return a reference to the scoped data bean.</p>
   *
   * @return reference to the scoped data bean
   */
  protected ApplicationBean1 getApplicationBean1() {
    return (ApplicationBean1) getBean("ApplicationBean1");
  }

  /**
   * <p>Return a reference to the scoped data bean.</p>
   *
   * @return reference to the scoped data bean
   */
  protected SessionBean1 getSessionBean1() {
    return (SessionBean1) getBean("SessionBean1");
  }

  /**
   * <p>Return a reference to the scoped data bean.</p>
   *
   * @return reference to the scoped data bean
   */
  protected RequestBean1 getRequestBean1() {
    return (RequestBean1) getBean("RequestBean1");
  }

  private void getPost() {
    FacesContext ctx = FacesContext.getCurrentInstance();
    HttpServletRequest req = (HttpServletRequest) ctx.getExternalContext().getRequest();

    String data = req.getParameter("data");
    String filtro = req.getParameter("filtro");

    String where = new String();
    if (data != null) {
      where = " where cast(dataHora as date) = '" + data + "' ";
    }

    Session s = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction t = s.beginTransaction();
    List<Post> l = s.createQuery("from Post " + where + " order by data_hora").list();

    String csv = "DataHora;Post;Posicao;PosicaoDB;Sentido;Status;Via;Resto\r\n";
    Encontrar enc = new Encontrar();

    for (int i = 0; i < l.size(); i++) {
      Post p = l.get(i);
      enc.encontarClasses(p.getPost());

      String linha = p.getDataHora() + ";" +
              p.getPost() + ";" +
              enc.getPosicao() + ";" +
              enc.getPosicao2() + ";" +
              enc.getSentido() + ";" +
              enc.getStatus() + ";" +
              enc.getVia() + ";" +
              enc.getResto();
      linha = linha.replace("\n", "");

      boolean ok = (((enc.getPosicao().length() > 0) || (enc.getPosicao2().length() > 0)) &&
              (enc.getSentido().length() > 0) &&
              (enc.getStatus().length() > 0) &&
              (enc.getVia().length() > 0));

      if (filtro.equals("0")) {
        csv += linha + "\r\n";
      } else if ((filtro.equals("1")) && (!ok)) {
        csv += linha + "\r\n";
      } else if ((filtro.equals("2")) && (ok)) {
        csv += linha + "\r\n";
      }
    }

    t.commit();
    download(csv.getBytes(), "post.csv", "text/csv");
  }

  void download(byte[] arquivo, String filename, String mimeType) {
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    response.addHeader("Content-Disposition", "attachment; filename=" + filename);
    response.setContentLength(arquivo.length);

    try {
      response.setContentType(mimeType);
      response.getOutputStream().write(arquivo);
      response.getOutputStream().flush();
      FacesContext.getCurrentInstance().responseComplete();
    } catch (Exception e) {
      error(e.getMessage());
    }
  }
}

